package mysql

import (
	"errors"
	"fmt"
	"gitee.com/xuxinzhi2206/corehub/nacos"
	"gitee.com/xuxinzhi2206/corehub/types"
	"github.com/spf13/viper"
	"gopkg.in/yaml.v2"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"log"
)

func WithMysql(hand func(db *gorm.DB) error) error {
	initNacos, err := nacos.GetConfig()
	config := types.Configs
	err = yaml.Unmarshal([]byte(initNacos), &config)
	if err != nil {
		return errors.New("failed to unmarshal")
	}

	if viper.GetBool("debug") {
		log.Printf("nacos读取连接配置 :::账号：%v,密码：%v,端口号：%v,ip：%v,数据库：%v", config.Mysql.Username, config.Mysql.Password, config.Mysql.Host, config.Mysql.Port, config.Mysql.Database)
	}

	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local", config.Mysql.Username, config.Mysql.Password, config.Mysql.Host, config.Mysql.Port, config.Mysql.Database)

	if viper.GetBool("debug") {
		log.Printf("mysql连接失败 :::%v", config)
	}

	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})

	if err != nil {
		return errors.New("mysql client failed,error: " + err.Error())
	}
	fmt.Println("mysql connection successful")
	fmt.Println("111111")
	defer func() {
		fmt.Println("关闭连接")
		dd, _ := db.DB()
		err := dd.Close()
		if err != nil {
			log.Printf("msyql close %v", err)

			return
		}
	}()
	return hand(db)
}
